﻿using _8Group.MES.MengIService;
using _8Group.MES.MengIService.DTO;
using _8Group.MES.Model.WM仓储管理;
using FourGroups.Project;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace _8Group.MES.MengService
{
    [ApiExplorerSettings(GroupName = "孟祥宇")]
    public class OutSousceService : ApplicationService, IOutSousceService
    {
        private readonly IRepository<WM_Outsource_Issue, int> _wmOutsourceRepository;
        public OutSousceService(IRepository<WM_Outsource_Issue, int> wmOutsourceRepository)
        {
            _wmOutsourceRepository = wmOutsourceRepository;
        }
        public async Task<string> GetOutSourceAsync(string? issueCode, string? workorderCode, string? vendorName, string? issueDate, int page, int limit)
        {
            var stock = await _wmOutsourceRepository.GetQueryableAsync();

            stock = stock.WhereIf(!string.IsNullOrEmpty(issueCode), x => x.IssueCode.Contains(issueCode));
            stock = stock.WhereIf(!string.IsNullOrEmpty(workorderCode), x => x.WorkorderCode.Contains(workorderCode));
            stock = stock.WhereIf(!string.IsNullOrEmpty(vendorName), x => x.VendorName.Contains(vendorName));
            stock = stock.WhereIf(!string.IsNullOrEmpty(issueDate), x => x.IssueDate==Convert.ToDateTime(issueDate) );

            int totalCount = stock.Count();

            stock = stock.OrderByDescending(c => c.Id).Skip((page - 1) * limit).Take(limit);

            return JsonConvert.SerializeObject(new { code = "0", data = stock.ToList(), count = totalCount, msg = "success" }, Formatting.Indented);
        }
        public async Task<int> AddOutSourceAsync(OutSourceDTO OutSource)
        {
            var n = AutoMapperExt.MapTo<WM_Outsource_Issue>(OutSource);
            await _wmOutsourceRepository.InsertAsync(n);
            return 1;
        }

        public async Task<int> UpdateOutSourceAsync(UpdateOutSourceDTO OutSource)
        {
            var model = AutoMapperExt.MapTo<WM_Outsource_Issue>(OutSource);
            await _wmOutsourceRepository.UpdateAsync(model);
            return 1;

        }

        public async Task<int> DeleteOutSourceAsync(int id)
        {
            await _wmOutsourceRepository.DeleteAsync(id, true);
            return 1;
        }

    }
}
